import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-04-16
 * Time: 19:36
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap() {
        for(int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            siftDown(parent,usedSize);
        }
    }

    public void swap(int i,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;

    }

    public void siftDown(int parent,int end) {
        int child = parent*2+1;
        while(child < end) {
            if(child + 1 < end && elem[child] < elem[child+1]) {
                child++;
            }
            //先找到左右孩子最大值，在进行和parent的比较
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }


    public boolean isFull() {
        return usedSize == elem.length;
    }

    public void offer(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
        siftUp(usedSize-1);
    }

    public void siftUp(int child) {
        int parent = (child-1)/2;
        while(child > 0) {
            if(elem[child] > elem[parent]) {
                swap(child,parent);
                child = parent;
                parent =(child-1) / 2;
            }else {
                break;
            }
        }
    }


    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int poll() {
        if(isEmpty()) {
            return -1;
        }
        int old = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize-1);
        return old;
    }

    public void heapSort() {
        int end = usedSize-1;
        while(end > 0) {
            swap(0,end);
            siftDown(0,end);
            end--;
        }
    }





}




